package com.ai.chat.service.impl;

import com.ai.chat.service.AIService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class AIServiceImpl implements AIService {

    @Value("${ai.api.url}")
    private String aiApiUrl;

    @Value("${ai.api.key}")
    private String aiApiKey;

    private final RestTemplate restTemplate = new RestTemplate();

    @Override
    public String generateResponse(String userMessage) {
        log.info("调用AI接口生成响应，用户消息: {}", userMessage);

        // 创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + aiApiKey);

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("prompt", userMessage);
        requestBody.put("max_tokens", 1024);
        requestBody.put("temperature", 0.7);

        HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);

        try {
            // 调用AI API
            ResponseEntity<Map> response = restTemplate.postForEntity(aiApiUrl, request, Map.class);

            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                // 解析响应结果（根据实际API返回格式调整）
                Map<String, Object> choices = (Map<String, Object>) ((java.util.List<Object>) response.getBody().get("choices")).get(0);
                String aiResponse = (String) choices.get("text");
                log.info("AI响应生成成功");
                return aiResponse;
            } else {
                log.error("AI接口调用失败，状态码: {}", response.getStatusCode());
                return "抱歉，AI服务暂时不可用，请稍后再试。";
            }
        } catch (Exception e) {
            log.error("AI接口调用异常", e);
            return "抱歉，生成响应时发生错误，请稍后再试。";
        }
    }
}